using System.Threading;
using System.Threading.Tasks;

namespace Runtime.Common.Utility
{
    public static class TaskEx
    {
        public static void FireAndForget(this Task task)
        {
            _ = task.ContinueWith(t =>
            {
                if (t.IsFaulted && t.Exception != null)
                {
                    // 获取主线程的调度器
                    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

                    // 在主线程上抛出异常
                    Task.Factory.StartNew(() => throw t.Exception.GetBaseException(), CancellationToken.None,
                        TaskCreationOptions.None, uiScheduler);
                }
            }, TaskScheduler.Default); // TaskScheduler.Default 使用默认任务调度器来防止死锁
        }
    }
}